<template>
  <div>
    <el-dialog
      :title="title"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="visible"
      :before-close="BeforClose"
    >
      <el-form
        :model="form"
        ref="form"
        v-loading="loading"
        :rules="rules"
        :class="method==='view'?'readonly':''"
        :disabled="method==='view'"
        label-width="110px"
      >
        <el-row :gutter="15">
          <el-col :span="11">
            <el-form-item
              label="故障类型"
              prop="serviceType"
            >
              <!-- <el-input se v-model="form.serviceType" placeholder="请输入"></el-input> -->
              <el-select
                v-model="form.serviceType"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option
                  v-for="(item,index) in ServiceTypeOption"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="区域"
              prop="serviceRange"
            >
              <!-- <el-input
                v-model="form.serviceRange"
                placeholder="请输入"
              ></el-input> -->
              <el-select
                @change="changeServiceRange"
                v-model="form.serviceRange"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option
                  v-for="(item,index) in ServiceRangeOption"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="11"
            v-if="form.serviceRange!=2"
          >
            <el-form-item
              label="关联房产编号"
              prop="projectId"
            >
              <el-select
                filterable
                v-model="form.projectId"
                placeholder="请选择"
                @change="changeProjectId"
                style="width:100%;"
              >
                <el-option
                  v-for="(item,index) in projectIdOption"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="11"
            v-if="form.serviceRange!=2"
          >
            <el-form-item
              label="公司名称"
              prop="companyId"
            >
              <el-select
                disabled
                filterable
                v-model="form.companyId"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option
                  v-for="(item,index) in sysCompanyOption"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="联系方式"
              prop="contactPhoneNumber"
            >
              <el-input
                v-model="form.contactPhoneNumber"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="故障设备"
              prop="relateDeviceType"
            >
              <el-select
                v-model="form.relateDeviceTypeName"
                placeholder="请选择"
                style="width:100%;"
                value-key="id"
                @change="changeRelateDeviceType">
                <el-option
                  v-for="(item,index) in relateDeviceTypeOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="服务费" prop="serviceFee">
              <el-input disabled v-model="form.serviceFee"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="报事/报修内容"
              prop="serviceDescription"
            >
              <el-input
                v-model="form.serviceDescription"
                type="textarea"
                placeholder="请输入报事/报修内容"
                :rows="4"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="上传多张图片"
              prop="files"
            >
              <el-upload
                action=""
                multiple
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :http-request="handleChanged"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img
                  width="100%"
                  :src="dialogImageUrl"
                  alt=""
                >
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="BeforClose"
          icon="el-icon-circle-close"
        >取 消</el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          v-if="method != 'view'"
          @click="doSubmit()"
        >提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, getIdCompany } from '@/api/market/repair/repair/cs_service'
export default {

  data () {
    var validatePass = (rule, value, callback) => {
      if (value.length != 11 || !(/^1[3-9]\d{9}$/.test(value))) {
        callback(new Error('手机号不合法'));
      } else {
        callback();
      }
    }
    return {
      title: '',
      method: '',
      visible: false,
      dialogWidth: '40%',
      loading: false,
      formLabelWidth: '80px',
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        projectId: [
          { required: true, message: '请选择房产编号' }
        ],
        serviceRange: [
          { required: true, message: '请选择区域' }
        ],
        relateDeviceType: [
          { required: true, message: '请选择故障设备' }
        ],
        serviceType: [
          { required: true, message: '请选择事故类型' }
        ],
        contactPhoneNumber: [
          { required: true, message: '请填写联系方式' }
        ],
        companyId: [
          { required: true, message: '请选择公司' }
        ],
        serviceDescription: [
          { required: true, message: '请填写报事/报修内容' }
        ],
      },
      form: {
        id: '',
        serviceBxNumber: '',//报事报修编号
        projectId: '',
        companyId: '',
        companyName: '',
        bindingPhone: '',
        serviceRange: '',
        relateDeviceType: '',
        serviceType: '',
        contactPhoneNumber: '',
        serviceStatus: '',
        repairDate: '',
        serviceDescription: '',
        files: '',
      },
      ServiceRangeOption: [],
      ServiceTypeOption: [{
        label: '报事',
        value: '1'
      }, {
        label: '报修',
        value: '2'
      }],
      projectIdOption: [],
      relateDeviceTypeOption: [],
      sysCompanyOption: [],
      fileList: [],
      fileLists: []
    }
  },
  components: {
  },
  methods: {
    changeServiceRange () {
      this.form.projectId = ''
      this.form.companyId = ''
      this.form.companyName = ''
      this.form.bindingPhone = ''
    },
    BeforClose () {
      this.fileList = []
      this.fileLists = []
      setTimeout(() => {
        this.visible = false
      }, 1)
    },
    // 根据房产编号进行公司名称绑定
    changeProjectId () {
      getIdCompany(this.form.projectId).then(res => {
        if (res.data.code === 0) {
          this.form.companyId = res.data.data.id
          this.form.companyName = res.data.data.name
          this.form.bindingPhone = res.data.data.contactPhone
          this.sysCompanyOption.push(res.data.data)
        }
      })
    },
    handleChanged (raw) {
      // for(var i=0;i<fileList.length;i++){
      // this.fileList.push(file.raw)
      // if (this.fileList.length === fileList.length) {
      //   this.formdata.append('file', this.fileList)
      // }
      // }
      this.fileLists.push(raw.file);
      // this.formdata.append('file', file.raw)
      // console.log(raw)
      // this.fileList = raw
    },
    init (method, id) {
      this.fileList = []
      this.fileLists = []
      this.method = method
      this.form.id = id
      if (method === 'add') {
        this.title = `新建报事报修`
      } else if (method === 'edit') {
        this.title = '修改报事报修'
      } else if (method === 'view') {
        this.title = '查看报事报修'
      }
      this.visible = true;

      //获取详情
      this.loading = false
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (method === 'view') { // 查看

        }
        // 区域
        let p1 = new Promise((resolve, reject) => {
          this.$http({
            url: '/admin/dict/type/service_range',
            method: 'get',
            params: {}
          }).then(({ data }) => {
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        })
        // 故障设备
        let p2 = new Promise((resolve, reject) => {
          this.$http({
            url: '/repair/repair/device/list',
            method: 'get',
            params: {}
          }).then(({ data }) => {
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        })
        // 请求关联房产编号的
        let p3 = new Promise((resolve, reject) => {
          this.$http({
            url: '/config/sysprojecttype/getEstateByPhone',
            method: 'get',
            params: {}
          }).then(({ data }) => {
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        })
        // 请求公司信息的
        // let p4 = new Promise((resolve, reject) => {
        //   this.$http({
        //     url: '/config/syscompany/getCompanyByPhone',
        //     method: 'get',
        //     params: {}
        //   }).then(({ data }) => {
        //     resolve(data)
        //   }).catch(err => {
        //     reject(err)
        //   })
        // })
        Promise.all([p1, p2, p3]).then((result) => {
          this.ServiceRangeOption = result[0].data
          this.relateDeviceTypeOption = result[1].data
          this.projectIdOption = result[2].data
          // this.sysCompanyOption = result[3].data
        })
      })
    },

    // 表单提交
    doSubmit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let formdata = new FormData()
          for (var key in this.form) {
            formdata.append(key, this.form[key])
          }
          this.fileLists.forEach(function (file) {
            // 因为要上传多个文件，所以需要遍历一下才行
            formdata.append('file', file);
          })
          // formdata.append('file', files);
          // this.formdata.append('csCustomerService', JSON.stringify(this.form))
          if (this.form.id) {
            putObj(formdata).then(data => {
              this.fileList = []
              this.fileLists = []
              setTimeout(() => {
                this.$message.success('修改成功')
                this.visible = false
                this.$emit('refreshDataList')
              }, 1)
            });
          } else {
            addObj(formdata).then(data => {
              this.fileList = []
              this.fileLists = []
              setTimeout(() => {
                this.$message.success('添加成功')
                this.visible = false
                this.$emit('refreshDataList')
              }, 1)
            })
          }
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    changeRelateDeviceType(val) {
      this.$set(this.form, 'relateDeviceType', val.id)
      this.$set(this.form, 'relateDeviceTypeName', val.name)
      this.$set(this.form, 'serviceFee', val.serviceFee)
    }
  }
}</script>

